<template>
  <view class="daily-recruitment">
    <view class="post-form">
      <!-- 基本信息 -->
      <view class="form-group">
        <text class="label">职位标题</text>
        <input
            type="text"
            v-model="formData.positionName"
            class="input"
            placeholder="请输入职位标题"
        />
        <text v-if="formErrors.positionName" class="error-text">{{ formErrors.positionName }}</text>
      </view>

      <view class="form-group">
        <text class="label">职位类型</text>
        <view
            class="picker-input"
            :class="{ 'error-border': formErrors.type }"
            @click="showTypePicker = true"
        >
          <text class="picker-text">{{ jobTypeText || '请选择职位类型' }}</text>
        </view>
        <text v-if="formErrors.type" class="error-text">{{ formErrors.type }}</text>
      </view>

      <view class="form-group">
        <text class="label">公司名称/雇主名称</text>
        <input
            type="text"
            v-model="formData.corporateName"
            class="input"
            placeholder="请输入公司名称/雇主名称"
        />
        <text v-if="formErrors.corporateName" class="error-text">{{ formErrors.corporateName }}</text>
      </view>

      <view class="form-group">
        <text class="label">工作地点</text>
        <input
            type="text"
            v-model="formData.location"
            class="input"
            placeholder="请输入工作地点"
        />
        <text v-if="formErrors.location" class="error-text">{{ formErrors.location }}</text>
      </view>

      <!-- 职位要求 -->
      <view class="form-group">
        <text class="label">经验要求</text>
        <view
            class="picker-input"
            :class="{ 'error-border': formErrors.experience }"
            @click="showExperiencePicker = true"
        >
          <text class="picker-text">{{ formData.experience || '请选择经验要求' }}</text>
        </view>
        <text v-if="formErrors.experience" class="error-text">{{ formErrors.experience }}</text>
      </view>

      <view class="form-group">
        <text class="label">薪资</text>
        <view class="flex items-center">
          <input
            type="number"
            v-model="formData.salary"
            class="input flex-1"
            placeholder="请输入薪资（如：200元/天）"
          />
          <text class="ml-[24rpx] text-[32rpx] text-blue-600">元/天</text>
        </view>
        
        <text v-if="formErrors.salary" class="error-text">{{ formErrors.salary }}</text>
      </view>

      <view class="form-group">
        <text class="label">工作时间</text>
        <input
            type="text"
            v-model="formData.timeFrame"
            class="input"
            placeholder="请输入工作时间（如：8:00-18:00）"
        />
        <text v-if="formErrors.timeFrame" class="error-text">{{ formErrors.timeFrame }}</text>
      </view>

      <view class="form-group">
        <text class="label">招聘人数</text>
        <input
            type="number"
            min="1"
            v-model="formData.number"
            class="input"
            placeholder="请输入招聘人数"
        />
        <text v-if="formErrors.number" class="error-text">{{ formErrors.number }}</text>
      </view>

      <!-- 职位描述 -->
      <view class=" remediation-group mb-[40rpx]">
        <text class="label">适合人群</text>
        <view class="flex flex-wrap gap-2">
          <view 
            v-for="item in suitablePersons" 
            :key="item.id"
            class="px-3 py-1 rounded-full border transition-all duration-200 cursor-pointer"
            :class="selectedGroupId === item.id ? 'bg-blue-600 border-blue-600 text-white' : 'bg-gray-100 border-gray-300 text-gray-600'"
            @click="selectGroup(item.id)"
          >
            <text class="text-[22rpx]">{{ item.name }}</text>
          </view>
        </view>
      </view>

      <view class="form-group">
        <text class="label">详细描述</text>
        <nut-textarea
            v-model="formData.description"
            class="textarea"
            placeholder="请详细描述工作内容、要求、福利等"
        />
        <text v-if="formErrors.description" class="error-text">{{ formErrors.description }}</text>
      </view>

      <!-- 招聘日期（开始-结束） -->
      <view class="form-group">
        <text class="label">招聘日期</text>
        <view class="flex gap-[20rpx]">
          <view
            class="picker-input flex-1"
            :class="{ 'error-border': formErrors.startdate }"
            @click="showStartDatePicker = true"
          >
            <text class="picker-text">{{ formData.startdate || '开始日期' }}</text>
          </view>
          <view class="flex items-center text-[#999] text-[24rpx]">至</view>
          <view
            class="picker-input flex-1"
            :class="{ 'error-border': formErrors.enddate }"
            @click="showEndDatePicker = true"
          >
            <text class="picker-text">{{ formData.enddate || '结束日期' }}</text>
          </view>
        </view>
        <text v-if="formErrors.startdate" class="error-text">{{ formErrors.startdate }}</text>
        <text v-if="formErrors.enddate" class="error-text">{{ formErrors.enddate }}</text>
      </view>


      <!-- 区域选择 -->
      <RegionSelector 
        v-model="regionLevel"
        @change="handleRegionChange"
      />

      <!-- 提交按钮 -->
      <nut-button class="submit-btn" @click="handleSubmit">发布招聘</nut-button>
    </view>

    <!-- 选择器弹窗 -->
    <nut-popup v-model:visible="showTypePicker" position="bottom" round>
      <nut-picker
          v-model="jobTypesValue"
          :columns="jobTypes"
          title="选择职位类型"
          @confirm="onTypeConfirm"
          @cancel="showTypePicker = false"
      />
    </nut-popup>

    <nut-popup v-model:visible="showExperiencePicker" position="bottom" round>
      <nut-picker
          :columns="experienceOptions.map(exp => ({ text: exp, value: exp }))"
          title="选择经验要求"
          @confirm="onExperienceConfirm"
          @cancel="showExperiencePicker = false"
      />
    </nut-popup>

    <!-- 日期选择器：开始与结束 -->
    <nut-calendar
      v-model:visible="showStartDatePicker"
      v-model="startDateValue"
      title="选择开始日期"
      @choose="onStartDateConfirm"
      @close="showStartDatePicker = false"
    />

    <nut-calendar
      v-model:visible="showEndDatePicker"
      v-model="endDateValue"
      title="选择结束日期"
      @choose="onEndDateConfirm"
      @close="showEndDatePicker = false"
    />

    <!-- 支付方式选择弹窗 -->
    <PaymentMethodModal 
      v-model="showPaymentModal" 
      :amount="totalAmount"
      @confirm="handlePaymentConfirm"
      @cancel="handlePaymentCancel"
    />
  </view>
</template>

<script setup lang="ts">
import {ref, reactive, onMounted} from 'vue'
import Taro from '@tarojs/taro'
import {post} from "@/utils/request";
// import {Textarea as nutTextarea} from '@nutui/nutui-taro';
// import {Popup as nutPopup} from '@nutui/nutui-taro';
// import {Picker as nutPicker} from '@nutui/nutui-taro';
// import {DatePicker as nutDatePicker} from '@nutui/nutui-taro';
// import {Button as nutButton} from '@nutui/nutui-taro';
import RegionSelector from '@/components/RegionSelector.vue';
import PaymentMethodModal from '@/components/PaymentMethodModal.vue';
import { useUserStore } from '@/store/user';

/** 表单数据类型 */
interface JobFormData {
  positionName: string
  type: string
  corporateName: string
  location: string
  experience: string
  salary: string
  timeFrame: string
  description: string
  number: string
  startdate: string,
  enddate: string,
}
/**定义获取职位类型接口*/
interface JobTypeColumn {
  update_time: number,
  create_time: number,
  name: string,
  id: number,
  pic: string
}

interface JobTypeItem {
  columns: JobTypeColumn;
  columnNames: string[];
  columnValues: (null | number | string)[];
}

const jobTypeText = ref()
const jobTypesValue = ref<string[]>([])

// 适合人群相关
const suitablePersons = ref<any[]>([]);
const selectedGroupId = ref<number>(0); // 默认为"不限"

/** 职位类型选项 */
const jobTypes = ref([
  {
    text:'',
    value:''
  }
  //'普工', '技工', '管理', '质检', '仓储', '后勤', '其他'
])

/** 经验要求选项 */
const experienceOptions = [
  '不限', '1年以下', '1-3年', '3-5年', '5年以上'
]
/**获取职位类型*/
getType()
function getType() {
  post('/dictionary/recruitmentDailyLabel').then(res => {
    jobTypes.value = res.data.map((item: JobTypeItem) => ({
      text: item.columns.name,
      value: item.columns.id.toString()
    }));
  })
}

/** 表单数据 */
const formData = reactive<JobFormData>({
  positionName: '',
  type: '',
  corporateName: '',
  location: '',
  experience: '',
  salary: '',
  timeFrame: '',
  description: '',
  number: '',
  startdate: '',
  enddate: '',
})

/**
 * 区域选择
 * @type {import('vue').Ref<string>}
 */
const regionLevel = ref("city");

// 区域价格
const fee = ref<string>('1'); //默认是区域是市级
const rangeType = ref<string>('1');

/**
 * 处理区域选择变化
 * @param data 区域选择数据
 */
const handleRegionChange = (data: { value: string; fee: number; range: string }) => {
  console.log("区域选择变化:", data);
  fee.value = String(data.fee);
  rangeType.value = data.range;
};

/** 表单验证状态 */
const formErrors = reactive<Partial<JobFormData>>({})

/** 选择器显示状态 */
const showTypePicker = ref(false)
const showExperiencePicker = ref(false)
const showStartDatePicker = ref(false)
const showEndDatePicker = ref(false)

/**
 * 日期选择器默认值
 * @description 为日期选择器提供下个月的默认值
 */
const startDateValue = ref<string>("")
const endDateValue = ref<string>("")

/** 表单验证 */
function validateForm(): boolean {
  const errors: Partial<JobFormData> = {}

  if (!formData.positionName.trim()) errors.positionName = '请输入职位标题'
  if (!formData.type) errors.type = '请选择职位类型'
  if (!formData.corporateName.trim()) errors.corporateName = '请输入公司名称/雇主名称'
  if (!formData.location.trim()) errors.location = '请输入工作地点'
  if (!formData.experience) errors.experience = '请选择经验要求'
  if (!formData.salary.trim()) errors.salary = '请输入薪资'
  if (!formData.timeFrame.trim()) errors.timeFrame = '请输入工作时间'
  if (!formData.description.trim()) errors.description = '请输入职位描述'
  if (!formData.number.trim()) errors.number = '请输入招聘人数'
  if (!formData.startdate) errors.startdate = '请选择开始日期'
  if (!formData.enddate) errors.enddate = '请选择结束日期'

  Object.assign(formErrors, errors)
  return Object.keys(errors).length === 0
}

const totalAmount = ref(0);

// 用户store
const userStore = useUserStore();

/**
 * 获取适合人群列表
 */
const getSuitablePersons = async () => {
  try {
    const res = await post("/dictionary/groupTypes");
    console.log("res==>人群",res.data)
    if (res.code === 0 && res.data) {
      // 根据接口返回的数据结构处理人群列表
      suitablePersons.value = res.data.map((item: any) => item.columns);
      suitablePersons.value.unshift({ id: 0, name: "不限" });
    }
  } catch (error) {
    console.error("获取适合人群列表失败:", error);
    // 设置默认人群列表作为备用
    suitablePersons.value = [
      { id: 0, name: "不限" },
      { id: 1, name: "学生" },
      { id: 2, name: "上班族" },
      { id: 3, name: "自由职业者" },
      { id: 4, name: "退休人员" }
    ];
  }
};

/**
 * 选择适合人群
 * @param groupId 人群ID
 */
const selectGroup = (groupId: number) => {
  selectedGroupId.value = groupId;
  
  // 显示选择提示
  const groupName = groupId === 0 ? '不限' : suitablePersons.value.find(item => item.id === groupId)?.name || '未知';
  Taro.showToast({
    title: `已选择：${groupName}`,
    icon: 'none',
    duration: 1500
  });
};

// 支付方式选择弹窗相关
const showPaymentModal = ref(false);
const currentTaskId = ref<number | null>(null);

// 日历确认回调
function onStartDateConfirm(val: any) {
  formData.startdate = formatCalendarValue(val)
  showStartDatePicker.value = false
}

function onEndDateConfirm(val: any) {
  formData.enddate = formatCalendarValue(val)
  showEndDatePicker.value = false
}

function formatCalendarValue(val: any): string {
  // 1) 直接字符串
  if (typeof val === 'string') return val
  // 2) 官方回调形如 { selectedValue: [YYYY, MM, DD] }
  if (val && Array.isArray(val.selectedValue)) {
    const [y, m, d] = val.selectedValue
    return `${y}-${String(m).padStart(2, '0')}-${String(d).padStart(2, '0')}`
  }
  // 3) 有些场景回调为数组 [YYYY, MM, DD, 'YYYY-MM-DD']
  if (Array.isArray(val)) {
    if (typeof val[3] === 'string' && val[3]) return val[3]
    const [y, m, d] = val
    if (y && m && d) return `${y}-${String(m).padStart(2, '0')}-${String(d).padStart(2, '0')}`
  }
  try {
    const d = new Date(val)
    const y = d.getFullYear()
    const m = String(d.getMonth() + 1).padStart(2, '0')
    const dd = String(d.getDate()).padStart(2, '0')
    return `${y}-${m}-${dd}`
  } catch {
    return ''
  }
}

/** 提交表单 */
function handleSubmit() {
  // 计算招聘日期天数间隔
  const startDate = new Date(formData.startdate);
  const endDate = new Date(formData.enddate);
  const dayDifference = Math.ceil((endDate.getTime() - startDate.getTime()) / (1000 * 60 * 60 * 24)) + 1;
  
  const amount = Number(formData.number) * Number(formData.salary) * dayDifference;
  console.log("amount", amount, "招聘人数:", Number(formData.number), "薪资:", Number(formData.salary), "天数:", dayDifference);
  console.log("formData", formData);
  console.log("区域选择:", regionLevel.value, "信息费:", fee.value, "范围类型:", rangeType.value);
  if (!validateForm()) {
    Taro.showToast({title: '请完善必填信息', icon: 'none', duration: 2000})
    return
  }
  const jobFormData: any = {
    ...formData,
    range: rangeType.value,
    fee: fee.value,
    groupTypes: selectedGroupId.value || 0 // 添加适合人群参数
  }
  Taro.showLoading({title: '发布中...'})

  // 新增：如果结束日期早于当前日期，可根据业务设置状态（可选）
  if (formData.enddate) {
    const currentTime = new Date().getTime()
    const endTime = new Date(formData.enddate).getTime()
    if (currentTime > endTime) {
      jobFormData.status = 1
    }
  }

  setTimeout(() => {
    Taro.hideLoading()

    // 计算招聘日期天数间隔
    const startDate = new Date(formData.startdate);
    const endDate = new Date(formData.enddate);
    const dayDifference = Math.ceil((endDate.getTime() - startDate.getTime()) / (1000 * 60 * 60 * 24)) + 1;
    
    const amount = Number(formData.number) * Number(formData.salary) * dayDifference;
    console.log("amount", amount, "招聘人数:", Number(formData.number), "薪资:", Number(formData.salary), "天数:", dayDifference);
    totalAmount.value = amount;

    //console.log("参数列表",jobFormData)
    post('/recruitmentDaily/save', jobFormData)
        .then(res => {
          console.log("res", res);
          if (res.code === 0) {
            // 重置表单
            Object.keys(formData).forEach((key) => {
              formData[key as keyof JobFormData] = "";
            });
            // tags.value.forEach((tag) => (tag.selected = false));
            Taro.showToast({title: '发布成功！', icon: 'success', duration: 2000,
              success: () => {
                // 显示支付方式选择弹窗
                showPaymentModal.value = true;
                // 保存任务ID用于后续支付
                currentTaskId.value = res.data;
              }
            })
          } else {
            Taro.showToast({title: '发布失败！', icon: 'error', duration: 2000})
          }
        })
  }, 2500)
}

/**
 * 处理支付方式确认
 * @param method 支付方式
 */
const handlePaymentConfirm = async (method: 'balance' | 'wechat') => {
  if (!currentTaskId.value) {
    Taro.showToast({
      title: "任务ID不存在",
      icon: "none",
    });
    return;
  }

  try {
    // 调用支付接口
    const payRes = await post("/pay/recruitmentDaily", {
      amount: totalAmount.value,
      bid: currentTaskId.value,
      vipType: 1,
      deductionBalance: method === 'balance' ? 1 : 0, // 余额支付传1，微信支付传0
    });
    console.log("payRes --->>>", payRes);

    if (payRes.code == 0) {
      if (method === 'wechat') {
        // 微信支付
        doPay(payRes.data);
      } else {
        if(payRes.data.code == 2){
        // 余额支付
          Taro.showToast({
            title: "支付成功！",
            icon: "success",
            duration: 2000,
          });
          // 更新用户余额
          const newBalance = (userStore.userInfo.balance || 0) - parseFloat(totalAmount.value.toString());
          userStore.updateBalance(newBalance);
          setTimeout(() => {
            Taro.navigateBack();
          }, 2000);
        }
        else{
          Taro.showToast({
            title: payRes.data.msg || "支付失败",
            icon: "none",
            duration: 2000,
          });
        }
      }
    } else {
      Taro.showToast({
        title: "支付失败",
        icon: "none",
      });
    }
  } catch (error) {
    console.error('支付失败:', error);
    Taro.showToast({
      title: "支付失败，请重试",
      icon: "none",
    });
  } finally {
    currentTaskId.value = null; // 清空任务ID
  }
};

/**
 * 处理支付取消
 */
const handlePaymentCancel = () => {
  currentTaskId.value = null; // 清空任务ID
  Taro.showToast({
    title: "已取消支付",
    icon: "none",
  });
};

// 支付发布任务费用（保留原函数用于兼容，已废弃）
// const payTask = async (id: number) => {
//   try {
//     const payRes = await post("/pay/recruitmentDaily", {
//       amount: totalAmount.value,
//       bid: id,
//       vipType: 1,
//     });
//     if (payRes.code == 0) {
//       doPay(payRes.data);
//       // Taro.showToast({
//       //   title: `任务发布成功！总金额：¥${totalAmount.value}`,
//       //   icon: "success",
//       //   duration: 3000,
//       // });
//     } else {
//       Taro.showToast({
//         title: "支付失败",
//         icon: "none",
//       });
//     }
//   } catch (error) {
//     console.error('支付失败:', error);
//     Taro.showToast({
//       title: "支付失败，请重试",
//       icon: "none",
//     });
//   } finally {
//     // isSubmitting.value = false; // 重置loading状态
//   }
// };

// 微信弹窗
const doPay = (param: any) => {
  (window as any).WeixinJSBridge.invoke(
    "getBrandWCPayRequest",
    {
      appId: param.appid, //公众号ID，由商户传入
      timeStamp: param.timeStamp, //时间戳，自1970年以来的秒数
      nonceStr: param.nonceStr, //随机串
      package: param.prepayId,
      signType: "RSA", //微信签名方式：
      paySign: param.paySign, //微信签名
    },
    function (param: any) {
      if (param.err_msg == "get_brand_wcpay_request:ok") {
        // 使用以上方式判断前端返回,微信团队郑重提示：
        //res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠，商户需进一步调用后端查单确认支付结果。
        Taro.showToast({
          title: "购买成功！",
          icon: "success",
          duration: 2000,
        });
      } else {
        Taro.showToast({ title: "购买失败！", icon: "error", duration: 2000 });
      }
    }
  );
};

/**
 * 页面初始化
 * @description 设置表单默认值，包括截止日期默认为下个月
 * @performance 在页面加载时一次性设置，避免重复计算
 */
onMounted(() => {
  // 初始化开始/结束日期为空，由用户选择
  
  // 获取适合人群数据
  getSuitablePersons();
})

/** 选择器确认事件 */
function onTypeConfirm(value: any) {
  if (value.selectedValue && value.selectedValue.length > 0){
    jobTypesValue.value = value.selectedValue
    //jobTypes.value = categoryOptions.value.find(item => item.value === String(val.selectedValue[0]))?.text
    jobTypeText.value = jobTypes.value.find(item => item.value === String(value.selectedValue[0]))?.text
  }
  formData.type = String(value?.selectedValue[0] || '')
  showTypePicker.value = false
}

function onExperienceConfirm(value: any) {
  formData.experience = value?.selectedValue[0] || ''
  showExperiencePicker.value = false
}

// 已移除截止日期确认，改为 onStartDateConfirm/onEndDateConfirm
</script>

<style lang="scss" scoped>
/* 基础容器样式 */
.daily-recruitment {
  background-color: #f5f5f5;
}
:deep(.region-selector) {
  margin: 0 !important;
  .nut-radio {
    margin-bottom: 0 !important;
  }
}
/* 表单容器样式 */
.post-form {
  background-color: white;
  border-radius: 16rpx;
  padding: 40rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
}

/* 表单组样式 */
.form-group {
  margin-bottom: 30rpx;
}

/* 标签样式 */
.label {
  display: block;
  margin-bottom: 8rpx;
  font-weight: bold;
  color: #555;
  font-size: 28rpx;
}

/* 输入框样式 */
.input, .picker-input {
  width: 100%;
  padding: 20rpx;
  border: 1rpx solid #ddd;
  border-radius: 8rpx;
  font-size: 28rpx;
  box-sizing: border-box;
  background-color: white;
}

:deep(.nut-textarea) {
  border: 1rpx solid #ddd;
  border-radius: 8rpx;
  padding: 20rpx;
}

/* 选择器输入框样式 */
.picker-input {
  display: flex;
  align-items: center;
  min-height: 76rpx;
  cursor: pointer;
}

.picker-text {
  color: #333;
  width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.picker-input placeholder {
  color: #999;
}

/* 文本域样式 */
.textarea {
  min-height: 180rpx;
  resize: vertical;
}

/* 错误提示样式 */
.error-text {
  color: #f44336;
  font-size: 24rpx;
  margin-top: 8rpx;
  display: block;
}

.error-border {
  border-color: #f44336 !important;
}

/* 提交按钮样式 */
.submit-btn {
  background-color: #1976d2 !important;
  color: white !important;
  width: 100%;
  margin-top: 40rpx;
  padding: 24rpx 40rpx;
  border-radius: 8rpx;
  font-size: 32rpx;
  font-weight: bold;
  border: none;
}

/* 输入框聚焦样式 */
input:focus, textarea:focus, .picker-input:focus {
  outline: none;
  border-color: #1976d2;
}
</style>